package com.qulai.web.controller.amazon_us;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONObject;
import com.qulai.amazon_us.domain.amazon_us.RecordUpload;
import com.qulai.amazon_us.domain.basic.Product;
import com.qulai.amazon_us.service.amazon_us.IRecordUploadService;
import com.qulai.amazon_us.service.basic.IProductService;
import com.qulai.common.utils.http.HttpUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.qulai.common.annotation.Log;
import com.qulai.common.core.controller.BaseController;
import com.qulai.common.core.domain.AjaxResult;
import com.qulai.common.enums.BusinessType;
import com.qulai.amazon_us.domain.amazon_us.AmazonUsUpload;
import com.qulai.amazon_us.service.amazon_us.IAmazonUsUploadService;
import com.qulai.common.utils.poi.ExcelUtil;
import com.qulai.common.core.page.TableDataInfo;

import static com.qulai.common.utils.ListUtils.listConvertToString;
import static com.qulai.common.utils.http.HttpUtils.amazon_us_to_xlsm;

/**
 * 上传记录Controller
 *
 * @author hunan
 * @date 2025-01-05
 */
@RestController
@RequestMapping("/amazon_us/upload")
public class AmazonUsUploadController extends BaseController {
    @Autowired
    private IAmazonUsUploadService amazonUsUploadService;

    @Autowired
    private IRecordUploadService recordUploadService;

    @Autowired
    private IProductService productService;

    /**
     * 查询上传记录列表
     */
    @PreAuthorize("@ss.hasPermi('amazon_us:upload:list')")
    @GetMapping("/list")
    public TableDataInfo list(AmazonUsUpload amazonUsUpload) {
        startPage();
        List<AmazonUsUpload> list = amazonUsUploadService.selectAmazonUsUploadList(amazonUsUpload);
        return getDataTable(list);
    }

    /**
     * 导出上传记录列表
     */
    @PreAuthorize("@ss.hasPermi('amazon_us:upload:export')")
    @Log(title = "上传记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AmazonUsUpload amazonUsUpload) {
        List<AmazonUsUpload> list = amazonUsUploadService.selectAmazonUsUploadList(amazonUsUpload);
        ExcelUtil<AmazonUsUpload> util = new ExcelUtil<AmazonUsUpload>(AmazonUsUpload.class);
        util.exportExcel(response, list, "上传记录数据");
    }

    /**
     * 获取上传记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('amazon_us:upload:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(amazonUsUploadService.selectAmazonUsUploadById(id));
    }

    /**
     * 新增上传记录
     */
    @PreAuthorize("@ss.hasPermi('amazon_us:upload:add')")
    @Log(title = "上传记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AmazonUsUpload amazonUsUpload) {
        amazonUsUpload.setStatus(0);

        Map<String, Object> params = new HashMap<>();
        params.put("opt_name", amazonUsUpload.getOptName());
        params.put("shop", amazonUsUpload.getShop());
        params.put("brand", amazonUsUpload.getBrand());
        params.put("brand_zip", amazonUsUpload.getBrandZip());
        params.put("platform", amazonUsUpload.getBasicPlatform());
        params.put("price", amazonUsUpload.getPrice());
        params.put("product_type", amazonUsUpload.getProductType());
        params.put("class_name", amazonUsUpload.getClassName());
        params.put("not_class_name_list", amazonUsUpload.getNotClassNameList());
        if (null == amazonUsUpload.getLimitImg()) {
            params.put("limit_img", 3);
        } else if (amazonUsUpload.getLimitImg() < 1) {
            params.put("limit_img", 1);
        } else if (amazonUsUpload.getLimitImg() > 9) {
            params.put("limit_img", 9);
        } else {
            params.put("limit_img", amazonUsUpload.getLimitImg());
        }

        if (null == amazonUsUpload.getPrice()) {
            params.put("price", 1);
        }
        params.put("upload_limit", amazonUsUpload.getUploadLimit());
        if (Objects.isNull(amazonUsUpload.getProductType())) {
            amazonUsUpload.setProductType("");
        }
        params.put("times", amazonUsUpload.getTimes());
        params.put("product_index", amazonUsUpload.getBasicProductIndex());

        int times = amazonUsUpload.getTimes();
        int uploadTaskNum = amazonUsUpload.getUploadTaskNum();
        if (times < 1){
            return error("第几轮输入有误，至少从第1轮开始");
        }

        if(uploadTaskNum<1){
            return error("上传任务数有误");
        }

        // 查询轮数是否合理
        String tableName = "record_upload_"+amazonUsUpload.getShop().toLowerCase();
        RecordUpload recordUpload = recordUploadService.selectRecordUploadLastOne(tableName);

        if (recordUpload != null) {
            int recordTimes = recordUpload.getTimes();

//
//            if ((times > recordTimes+1) || (times < recordTimes)) {
//                return error("第几轮输入有误，上次提交是第:"+recordTimes+"轮");
//            }

        }

        //todo 暂时采用上传和制作分离
        JSONObject obj = new JSONObject(params);
        amazonUsUpload.setRemark(obj.toJSONString());
        amazonUsUpload.setUpdateBy(getUsername());


        int count=0;
        for (int i = 0; i < uploadTaskNum; i++) {
            amazonUsUploadService.insertAmazonUsUpload(amazonUsUpload);
            count++;
        }
        return toAjax(count);
    }

    /**
     * 修改上传记录
     */
    @PreAuthorize("@ss.hasPermi('amazon_us:upload:edit')")
    @Log(title = "上传记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AmazonUsUpload amazonUsUpload) {
        amazonUsUpload.setUpdateBy(getUsername());

        Map<String, Object> params = new HashMap<>();
        params.put("opt_name", amazonUsUpload.getOptName());
        params.put("shop", amazonUsUpload.getShop());
        params.put("brand", amazonUsUpload.getBrand());
        params.put("brand_zip", amazonUsUpload.getBrandZip());
        params.put("platform", amazonUsUpload.getBasicPlatform());

        params.put("price", amazonUsUpload.getPrice());
        params.put("product_type", amazonUsUpload.getProductType());
        params.put("class_name", amazonUsUpload.getClassName());
        params.put("not_class_name_list", amazonUsUpload.getNotClassNameList());
        if (null == amazonUsUpload.getLimitImg()) {
            params.put("limit_img", 3);
        } else if (amazonUsUpload.getLimitImg() < 1) {
            params.put("limit_img", 1);
        } else if (amazonUsUpload.getLimitImg() > 9) {
            params.put("limit_img", 9);
        } else {
            params.put("limit_img", amazonUsUpload.getLimitImg());
        }
        if (null == amazonUsUpload.getPrice()) {
            params.put("price", 1);
        }
        params.put("upload_limit", amazonUsUpload.getUploadLimit());
        if (Objects.isNull(amazonUsUpload.getProductType())) {
            amazonUsUpload.setProductType("");
        }
        params.put("times", amazonUsUpload.getTimes());
        params.put("product_index", amazonUsUpload.getBasicProductIndex());


        //todo 暂时采用上传和制作分离
        JSONObject obj = new JSONObject(params);
        amazonUsUpload.setRemark(obj.toJSONString());
        amazonUsUpload.setUpdateBy(getUsername());

        return toAjax(amazonUsUploadService.updateAmazonUsUpload(amazonUsUpload));
    }

    /**
     * 删除上传记录
     */
    @PreAuthorize("@ss.hasPermi('amazon_us:upload:remove')")
    @Log(title = "上传记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(amazonUsUploadService.deleteAmazonUsUploadByIds(ids));
    }


    /**
     * 查询本轮还有多少可以上架的
     */
    @PreAuthorize("@ss.hasPermi('amazon_us:upload:getThisTimesRestNum')")
    @GetMapping("/getThisTimesRestNum")
    public AjaxResult getThisTimesRestNum(AmazonUsUpload amazonUsUpload) {

        String shop = amazonUsUpload.getShop();
        String brand = amazonUsUpload.getBrand();
        Integer  times = amazonUsUpload.getTimes();
        List<String> basicPlatformList = amazonUsUpload.getBasicPlatform();
        String basicProductIndex = amazonUsUpload.getBasicProductIndex();

        if (shop == null || shop.isEmpty() ||
                brand == null || brand.isEmpty() ||
                basicProductIndex ==null || basicProductIndex.isEmpty() ||
                times == null || times == 0) {
            return error("请填写 '店铺、品牌、第几轮上传、主图类型' 后查询");
        }

        List<String> notClassNameList = amazonUsUpload.getNotClassNameList();

        String tables = "record_upload_"+shop.toLowerCase();

        int count =  productService.selectProductRestNum(brand,notClassNameList,times,tables,basicPlatformList,basicProductIndex);
        return success(count);
    }


}
